import datetime
from hmac import digest
from multiprocessing import Process,Queue
import os,time,random

# 进程学习
# def write(q):
#     print(f'Process to write: {os.getpid()}')
#     for value in ['A','B','C','D']:
#         print(f'Put {value} to queue...',value)
#         q.put(value)
#         time.sleep(random.random())
# def read(q):
#     print('Process to read: %s' % os.getpid())
#     while True:
#         value = q.get(True)
#         print(f'Get {value} from queue.',value)
#
#
# if __name__ == '__main__':
#     q = Queue()
#     pr = Process(target=read,args=(q,))
#     pw = Process(target=write,args=(q,))
#
#     pr.start()
#     pw.start()
#
#     pw.join()
#     pr.terminate()

# # 线程学习
import threading
# balance = 0
# lock = threading.Lock()
#
# def change_it(n):
#     global balance
#     balance = balance + n
#     balance = balance - n
#
# def run_thread(n):
#     for i in range(2000000):
#         lock.acquire()
#         try:
#             change_it(n)
#         finally:
#             lock.release()
#
# t1 = threading.Thread(target=run_thread,args=(11,))
# t2 = threading.Thread(target=run_thread,args=(99,))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print(balance)

## TreadLocal对象
"""
ThreadLocal最常用的地方就是为每个线程绑定一个数据库连接，HTTP请求，用户身份信息等，这样一个线程的所有调用到的处理函数都可以非常方便地访问这些资源。
下面示例打印的内容：
Hello, alex (in Threading-t1)
Hello, jason (in Threading-t2)
"""
# local_school = threading.local()
#
# def process_student():
#     std = local_school.student
#     print(f'Hello, {std} (in {threading.current_thread().name})\n')
#
# def process_thread(name):
#     local_school.student = name
#     process_student()
#
# t1 = threading.Thread(target=process_thread,args=('alex',),name="Threading-t1")
# t2 = threading.Thread(target=process_thread,args=('jason',),name="Threading-t2")
# t1.start()
# t2.start()
# t1.join()
# t2.join()


"""
# 000：给微信头像添加数字
"""
# from PIL import Image,ImageDraw,ImageFont
#
# number = 'js2thon'
# color = (0,0,0)
# windows_font = 'Arial.ttf'
#
# def draw_text(text,fill_color,windows_font):
#     im = Image.open('face.jpeg')
#     x,y = im.size
#     draw = ImageDraw.Draw(im)
#     font = ImageFont.truetype(windows_font,20)
#     draw.text((x-80,17),text,fill_color,font)
#
#     im.save('new_face.jpeg')
#
# draw_text(number,color,windows_font)

"""
# 001：生成激活码
"""
# import uuid
#
# def create_code(code_num,code_length):
#     # 生成num个激活码，每个激活码的长度length
#     result = []
#     while True:
#         uuid_id = uuid.uuid1()
#         temp = str(uuid_id).replace('-','')[:code_length]
#         if not temp in result:
#             result.append(temp)
#         if len(result) == code_num:
#             break
#     return result
#
# print(create_code(10,20))

"""
# 025: 操作电脑
"""
# import requests
# import pyaudio
# import wave
# import base64
# import webbrowser
# from aip import AipSpeech
# import urllib.parse
#
# CHUNK = 1024
# FORMAT = pyaudio.paInt16
# RATE = 8000
# CHANNELS = 1
# RECORD_SECONDS = 5
#
# APP_ID = "25739248"
# API_KEY = "6claF6VOWys82mmbRT29xOaf"
# SECRET_KEY = "6rGeRnpBFxHnpiDm6Lmm1n3G1DvWZrvn"
#
# def record_wave(to_dir=None):
#     if to_dir is None:
#         to_dir = "./"
#
#     pa = pyaudio.PyAudio()
#     stream = pa.open(format= FORMAT,
#                      channels= CHANNELS,
#                      rate = RATE,
#                      input= True,
#                      frames_per_buffer= CHUNK
#                      )
#     print("* recording")
#
#     save_buffer = []
#     for i in range(0,int(RATE / CHUNK * RECORD_SECONDS)):
#         audio_data = stream.read(CHUNK)
#         save_buffer.append(audio_data)
#
#     print("*.done recording")
#
#     stream.stop_stream()
#     stream.close()
#     pa.terminate()
#
#     file_name = datetime.datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav"
#     if to_dir.endswith('/'):
#         file_path = to_dir + file_name
#     else:
#         file_path = to_dir + "/" + file_name
#
#     wf = wave.open(file_path,'wb')
#     wf.setnchannels(CHANNELS)
#     wf.setsampwidth(pa.get_sample_size(FORMAT))
#     wf.setframerate(RATE)
#     wf.writeframes(b''.join(save_buffer))
#     wf.close()
#
#     return file_path
#
# def browser_open_text(text):
#     if text is None:
#         return None
#     if text.startswith("百度"):
#         url = f"http://www.baidu.com/s?wd={urllib.parse.quote(text[2:-1])}"
#         print(url)
#     elif text.startswith("谷歌") or text.startswith("google"):
#         url = "http://www.google.com"
#     elif text.startswith("必应") or text.startswith("bing"):
#         url = "http://cn.bing.com"
#     else:
#         return "听不懂"
#
#     webbrowser.open_new_tab(url)
#
# if __name__ == '__main__':
#     to_dir = "./"
#     file_path = record_wave(to_dir)
#     with open(file_path,'rb') as f:
#         audio_data = f.read()
#     print(file_path)
#     client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
#     result = client.asr(audio_data, 'wav', 8000, {'dev_pid': 1537, })
#     # print(result)
#     result_text = result["result"][0]
#     print(result_text)
#     browser_open_text(result_text)

# 百度人工智能中心：NLP
# from aip import AipNlp

# APP_ID = "25739744"
# API_KEY = "dNawcuLFAR39h6Cx3aeyr9Vw"
# SECRET_KEY = "D2CnxWUnVUtnjM4tEx8R51VxF79xHZWX"
#
# client = AipNlp(APP_ID,API_KEY,SECRET_KEY)
# text = "上海市松江区沪亭北路618弄"
# print(client.lexer(text))

# from pyhanlp import *
# import re
# from collections import Counter
#
# def check_address(value):
#     if not value:
#         return '其他','其他'
#     CRFnewSegment = HanLP.newSegment("crf")
#     address_list = CRFnewSegment.seg(value)
#     dict = {}
#     for i in address_list:
#         dict[str(i.word)] = [str(i.nature)]
#
#     print(dict)
#     ADDR_CODE = r'(ns|nsf)'  # 地址：ns|nsf  || 姓名：nr
#     addr_count = len(list(filter(lambda x:x==['ns'] or x ==['nsf'],dict.values())))
#
#     # addr_dict = Counter(str(value) for value in dict.values() if str(value) == "['ns']" or str(value) == "['nsf']")
#     # addr_count1 = addr_dict["['ns']"] + addr_dict["['nsf']"]
#
#
#     for addr,code in dict.items():
#         code = str(code)
#         if re.search(ADDR_CODE,code) and addr_count >= 3:
#             return '地址', value
#         else:
#             return '非法输入', value
#
#
# print(check_address('中国上海市松江区'))


# import bisect
# import random
# SIZE = 7
# random.seed(1729)
# my_list = []
# for i in range(SIZE):
#     new_item = random.randrange(SIZE * 2)
#     bisect.insort(my_list,new_item)
#     print('%2d->' %new_item,my_list)


# class Bus:
#     def __init__(self,passengers=None):
#         if passengers is None:
#             self.passengers = []
#         else:
#             self.passengers = list(passengers)
#     def pick(self,name):
#         self.passengers.append(name)
#     def drop(self,name):
#         self.passengers.remove(name)
#
# import copy
# bus1 = Bus(['Alice','Bill','Claire','David'])
# bus2 = copy.copy(bus1)
# bus3 = copy.deepcopy(bus1)
#
# bus1.drop('Bill')
# print(bus2.passengers)
# print(bus3.passengers)

import os,hashlib

def encrypt_password(password):
    salt = os.urandom(8)
    print(f'salt:{salt}')
    result = hashlib.sha256(password.encode()+salt).hexdigest()
    return salt,result

# print(encrypt_password('thisispass123'))


import hmac,random

def hmac_md5(key,s):
    return hmac.new(key.encode('utf-8'),s.encode('utf-8'),'MD5').hexdigest()

class User:
    def __init__(self,username,password):
        self.username = username
        self.key = ''.join([chr(random.randint(48,122)) for i in range(20)])
        self.password = hmac_md5(self.key,password)

db = {
    'michael':User('michael','123456'),
    'bob':User('bob','abc99')
}

def login(username,password):
    user = db[username]
    print(user.password)
    return user.password == hmac_md5(user.key,password)

print(login('michael','123456'))

import rest_framework_jwt



